<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>ChatGPT</title>
  <!-- 引入样式 -->
  <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
</head>
<body>
<div id="app">
  <el-input type="hidden" v-model="uuid" :disabled="true"></el-input>
  <el-input type="textarea" placeholder="请输入你的问题" v-model="question" autosize></el-input>
  <div style="margin: 20px 0;"></div>
  <el-button type="primary" size="small" @click="search">查询</el-button>
  <div style="margin: 20px 0;"></div>
  <el-input type="textarea" placeholder="ChatGPT的回答" v-model="answer" autosize></el-input>
</div>
</body>
<!-- 引入vue -->
<script src="https://unpkg.com/vue@2/dist/vue.js"></script>
<!-- 引入组件库 -->
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<!-- 引入axios -->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
  new Vue({
    el: '#app',
    data: function () {
      return {
        visible: false,
        uuid: "",
        question: "",
        answer: "",
        eventSource: null,
        alertMsg: ""
      }
    },
    mounted() {
      // 在页面加载时，先请求接口获取uuid，并建立SSE连接
      axios.get('/chat/getUUID')
              .then((response) => {
                console.log(response);
                this.uuid = response.data.uuid;
                this.connect();
              })
              .catch((error) => {
                console.error('Failed to get UUID:', error);
              });
    },
    methods: {
      connect() {
        // 建立SSE连接
        this.eventSource = new EventSource(`/chat/connect?uuid=${this.uuid}`);
        this.eventSource.onmessage = (event) => {
          // 将收到的消息累加到answer上
          this.answer += event.data;
        };
        this.eventSource.onerror = (error) => {
          console.error('SSE connection error:', error);
          this.eventSource.close();
        };
      },
      search() {
        if (this.check()) {
          // 清空回答
          this.answer = "";
          // 发起POST请求
          let data = {
            uuid: this.uuid,
            question: this.question
          };
          axios.post('/chat/ask', data)
                  .then(() => {
                    // this.question = '';
                  })
                  .catch((error) => {
                    console.error('Failed to ask question:', error);
                  });
        }
      },
      check() {
        if (!this.uuid) {
          this.alertMsg = "未获取到访问许可，请刷新页面";
          this.open();
          return false;
        }
        if (!this.question) {
          this.alertMsg = "请输入你的问题";
          this.open();
          return false;
        }
        return true;
      },
      open() {
        this.$alert(`${this.alertMsg}`, '提醒', {
          confirmButtonText: '确定'
        });
      }
    }
  })
</script>
</html>